package com.sysmanage.permissions.controls;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import com.sysmanage.common.tools.page.Pagination;
import com.sysmanage.common.tools.util.ArgumentMemoryUtils;
import com.sysmanage.common.tools.util.DictionaryMemoryUtils;
import com.sysmanage.common.tools.util.Encrypt;
import com.sysmanage.framework.controls.struts2.BaseTg;
import com.sysmanage.permissions.ConstCode;
import com.sysmanage.permissions.model.CloneUsers;
import com.sysmanage.permissions.model.Groups;
import com.sysmanage.permissions.model.Users;
import com.sysmanage.permissions.service.IGroupService;
import com.sysmanage.permissions.service.ILogService;
import com.sysmanage.permissions.service.IUserService;

/** 
  * @ClassName: UserTg 
  * @Description: 用户控制层
  * @author XXXX@163.com
  * @date 2011-9-26 上午9:30:21 
  *  
  */
/** 
  * @ClassName: UserTg 
  * @Description: TODO(这里用一句话描述这个类的作用) 
  * @author XXX@163.com
  * @date 2011-11-26 上午10:18:01 
  *  
  */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("permissions.userControl")
public class UserTg extends BaseTg{
	
	
	@Autowired
	private ILogService logService;
	/** 
	  * @Fields userService : IUserService接口spring注入
	  */ 
	@Autowired
	private IUserService userService;
	@Autowired
	private IGroupService groupService;

	
	/** 
	  * @Fields user : struts2.0自动接收
	  */ 
	private Users user;
	
	/** 
	  * @Fields id : 删除、更新用户所需的id，用户添加到组里面的用户id
	  */ 
	private String id;

	/** 
	  * @Fields groupId : 用户添加到组里面的组id
	  */ 
	private String groupId;
	private String groupName;
	private String loginids;
	private String q;

	
	private String newPassword;
	
	public String getQ() {
		return q;
	}

	public void setQ(String q) {
		this.q = q;
	}

	public String getLoginids() {
		return loginids;
	}

	public void setLoginids(String loginids) {
		this.loginids = loginids;
	}
	/** 
	  * @Fields backgroundImage : 修改背景图片时的图片名 
	  */ 
	private String backgroundImage;
	
	public String getBackgroundImage() {
		return backgroundImage;
	}

	public void setBackgroundImage(String backgroundImage) {
		this.backgroundImage = backgroundImage;
	}
	

	//文件上传参数
	
	private File[] upload;// 实际上传文件
	private String[] uploadContentType; // 文件的内容类型
	private String[] uploadFileName; // 上传文件名
	
	/** 
	  * @Title: index 
	  * @Description: 用户首页
	  * @param @return
	  * @return String
	  * @throws 
	  */
	public String index(){		
		return this.SUCCESS;
	}
	
	/** 
	  * @Title: find 
	  * @Description: 根据用户id查找用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void find(){
		Users user = this.userService.findById(Integer.valueOf(id));

		List<Users> list = new ArrayList<Users>();
		if(null != user){
			//解码用户密码
			/*
			Encrypt enc = new Encrypt();
			if(user.getPassword()!=null)
			{
				user.setPassword(enc.desString(user.getPassword()));
			}
			*/
			list.add(user);
		}
		
		JSONArray jsonArray = JSONArray.fromObject(doOther(userService.convert(list,true)));
		//现在一个用户只能有一个组
		Iterator<Groups> it = user.getGroups().iterator();
		
		
		while(it.hasNext()){
			Groups temp = it.next();
			returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"" + temp.getId() + "\",\"parentName\":\"" + temp.getName() + "\"}",response);
			return;
		}
		returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"\",\"parentName\":\"\"}",response);
		
	}
	
	/** 
	  * @Title: save 
	  * @Description: 保存用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void save(){
		logService.log("创建"+user.toString(), "创建");
		Encrypt enc = new Encrypt();
		user.setPassword(enc.encString(newPassword));
		user.setStatus(ConstCode.STATUS_ENABLE);
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		String date = format.format(new Date());
		user.setRegisterdate(date);
		
		user.setStatus(ConstCode.STATUS_ENABLE);
		
		if(null != groupId && !"".equals(groupId)){
			if(this.userService.saveToGroup(groupId, user)){
				reloadMemory();
				returnJsion("{\"success\":\"true\"}",response);
			}else{
				returnJsion("{\"error\":\"true\"}",response);
			}
		}else{
			boolean saveOK= true;
			saveOK = this.userService.saveUser(user);
			
			if(saveOK)
			{
				reloadMemory();
				returnJsion("{\"success\":\"true\"}",response);
			}else{
				returnJsion("{\"error\":\"true\"}",response);
			}
		}
		
		
	}
	
	/** 
	  * @Title: del 
	  * @Description: 根据id删除用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void del(){
		boolean ret = false;
		if(null != id && !"".equals(id))
		{
			String []userArray = id.split(",");
			
			for(int i=0;i<userArray.length;i++)
			{
				
				if(userArray[i]!=null&&!("".equals(userArray[i])))
				{
					Users delUser = userService.findById(Integer.valueOf(userArray[i]));
					logService.log("删除"+delUser.toString(), "删除");
					delUser.setStatus(ConstCode.STATUS_DELETE);
					ret = this.userService.alter(delUser);
					if(!ret)
						break;
				}
			}
		}
		if(ret){
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	public void getOrgTree(){
		if(id!=null&&id.startsWith("D"))
		{
			id = id.substring(1);
		}
		List<Map<String,Object>> list = this.userService.getDeptUserTree(id);
		outJsonPlainString(response, JSONArray.fromObject(list).toString());
	}	
	/** 
	  * @Title: getPage 
	  * @Description: 获取用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getPage(){
		if("new".equals(q))
		{
			page = 1;
			q = null;
		}
		if(user==null)
		{
			user = new Users();
			user.setCompanyId(this.getCurrentUserCompanyID());
		}
		else if(user.getCompanyId()==null)
		{
			if(!ArgumentMemoryUtils.getInstance().getValueByName("", "1").equals(this.getCurrentUserCompanyID()+""))
			{
				user.setCompanyId(this.getCurrentUserCompanyID());
			}
		}
		Pagination p =  this.userService.getPageList(user, page, rows,sort,order);
		
		List<Users> list = p.getList();
		List lists = doOther(userService.convert(list,false));	
		JSONArray jsonArray = JSONArray.fromObject(lists);
		String baseStr = "{\"total\":" + p.getTotalCount() + ",\"rows\":";
		baseStr = baseStr + jsonArray.toString() + "}";
		returnJsion(baseStr,response);
	}
	
	/** 
	  * @Title: getPage 
	  * @Description: 获取用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getList(){
		if(user==null)
		{
			user = new Users();
			user.setCompanyId(this.getCurrentUserCompanyID());
		}
		else if(user.getCompanyId()==null)
		{
			if(!ArgumentMemoryUtils.getInstance().getValueByName("", "1").equals(this.getCurrentUserCompanyID()+""))
			{
				user.setCompanyId(this.getCurrentUserCompanyID());
			}
		}
		String hql = "from Users where companyId = "+user.getCompanyId();
		List<Users> list = this.userService.findList(hql);
		List lists = doOther(userService.convert(list,false));	
		JSONArray jsonArray = JSONArray.fromObject(lists);
		String baseStr = "{\"total\":" + list.size() + ",\"rows\":";
		baseStr = baseStr + jsonArray.toString() + "}";
		returnJsion(baseStr,response);
	}
	/** 
	  * @Title: getGroupPage 
	  * @Description: 根据组名查人员
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getGroupPage(){
		if(groupName==null || "".equals(groupName)){
			Pagination p =  this.userService.getPageList(user, page, rows,sort,order);
			List<Users> list = p.getList();
			List lists = doOther(userService.convert(list,false));	
			JSONArray jsonArray = JSONArray.fromObject(lists);
			String baseStr = "{\"total\":" + p.getTotalCount() + ",\"rows\":";
			baseStr = baseStr + jsonArray.toString() + "}";
			returnJsion(baseStr,response);
		}else{
			List<Groups> groupList = groupService.getGroups(groupName);
			List<Users> list = new ArrayList<Users>();
			List lists = new ArrayList();
			Map<String,String> map = new HashMap<String,String>();
			for(Groups group : groupList){
				Set<Users> user =  group.getUsers();
				for(Users u : user){
					list.add(u);
				}
			}
			lists =doOther(userService.convert(list,false));
			JSONArray jsonArray = JSONArray.fromObject(lists);
			String baseStr = "{\"total\":" + lists.size() + ",\"rows\":";
			baseStr = baseStr + jsonArray.toString() + "}";
			returnJsion(baseStr,response);
		}
	}
	
	
	/** 
	  * @Title: update 
	  * @Description: 更新用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void update(){
		boolean ret = false;
		logService.log("更新"+user.toString(), "更新");
		//加密用户密码
		//先判断用户的密码是否是显示的虚拟密码
		Users tmpUser = userService.findById(user.getId());
		String pass = tmpUser.getPassword();
		Encrypt enc = new Encrypt();
		if(newPassword!=null&&newPassword.length()>1)
			pass = enc.encString(newPassword);
		
		Set<Groups> groups = tmpUser.getGroups();
		
		try {
			BeanUtils.copyProperties(tmpUser, user);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tmpUser.setPassword(pass);
		tmpUser.setGroups(groups);
		ret = this.userService.alter(tmpUser);
		/*
		if(null != groupId && !"".equals(groupId)){
			ret = this.userService.alterToGroup(user,groupId);
		}else{
			ret = this.userService.alter(user);
		}
		*/

		if(ret){
			reloadMemory();
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
		
	}
	/** 
	  * @Title: modifyPS 
	  * @Description: 修改用户密码
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void modifyPS(){
		boolean ret = false;
		logService.log("更新"+user.toString(), "更新");
		//加密用户密码
		//先判断用户的密码是否是显示的虚拟密码
		Users tmpUser = userService.findById(this.getUserID());
		Encrypt enc = new Encrypt();
		String oldPs = user.getPassword();
		if(oldPs!=null&&oldPs.length()>1)
		{
			oldPs = enc.encString(oldPs);
		}
		if(oldPs.equals(tmpUser.getPassword())&&user.getExt1()!=null)
		{
			tmpUser.setPassword(enc.encString(user.getExt1()));
			ret = this.userService.alter(tmpUser);
		}
		if(ret){
			reloadMemory();
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
		
	}	
	/*
	 * 数据库密码加密第一次初始化
	 */
	
	public void batchUpdatePasswd(){
		Encrypt enc = new Encrypt();
		System.out.println("开始更新用户密码");
		List<Users> users = this.userService.getAll();		
		for(Iterator<Users> iter=users.iterator();iter.hasNext();){
			
			Users tmpUser = iter.next();
			if (tmpUser.getUsertype()!=null&&tmpUser.getUsertype()==3)
			{
				//tmpUser.setPassword(enc.desString(tmpUser.getPassword()));
				tmpUser.setPassword(enc.encString(tmpUser.getPassword()));
				userService.alter(tmpUser);
			}
		}
		System.out.println("更新用户密码结束");
		/*
		System.out.println("开始更新TDS密码");
		//批量变更密码到TDS
		String ret = userService.batchSyncAllUserToTDS();
		System.out.println(ret);
		String baseStr = "{\"message\":" + ret  + "}";
		System.out.println("更新TDS密码结束");
		*/
		returnJsion("OK",response);
	}
	
	/** 
	  * @Title: getAllUsers 
	  * @Description:获得所有用户的下拉列表JSON 
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getAll(){
		try{
			List<Users> users = this.userService.getAll();
			List<Map<String,String>> maps = new ArrayList<Map<String,String>>();
			for(Iterator<Users> iter=users.iterator();iter.hasNext();){
				Map<String,String> map = new HashMap<String,String>();
				Users user = iter.next();
				map.put("id", user.getId()+"");
				map.put("loginid", user.getLogonid());
				map.put("name", user.getName());
				maps.add(map);
			}
			JSONArray json = JSONArray.fromObject(maps);
			outJsonUTFString(response, json.toString());
		}catch(Exception e){
			e.printStackTrace();
			outJsonUTFString(response, "[]");
		}
	}

	public void getGroupOtherPage(){
		Integer groupId = null;
		try{
			if(id!=null&&!("".equals(id)))
				groupId = Integer.valueOf(id);
		}catch(Exception e)
		{
			groupId = null;
		}
		if("new".equals(q))
		{
			page = 1;
			q = null;
		}
		Pagination p =  this.userService.getGroupOtherPageList(groupId,user, page, rows,sort,order);
		
		List<Users> list = p.getList();
		List lists = doOther(userService.convert(list,false));	
		JSONArray jsonArray = JSONArray.fromObject(lists);
		String baseStr = "{\"total\":" + p.getTotalCount() + ",\"rows\":";
		baseStr = baseStr + jsonArray.toString() + "}";
		returnJsion(baseStr,response);

	}	
	/** 
	  * @Title: getItems 
	  * @Description: 获取用户信息、获取具体组的用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getItems(){
		List<Users> list = null;
		if(null != id && !"".equals(id)){
			list = this.userService.getGroupAll(Integer.valueOf(id));
		}else{
			list = this.userService.getAll();
		}
		JSONArray json = JSONArray.fromObject(doOther(userService.convert(list,false)));
		String baseStr = "{\"total\":" + list.size() + ",\"rows\":";
		baseStr = baseStr + json.toString() + "}";
		returnJsion(baseStr,response);
	}
	/** 
	  * @Title: getGroupAllPage 
	  * @Description: 获取用户信息、获取具体组的用户信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void getGroupAllPage(){
		Integer groupId = null;
		try{
			if(id!=null&&!("".equals(id)))
				groupId = Integer.valueOf(id);
		}catch(Exception e)
		{
			groupId = null;
		}
		
		Pagination p =  this.userService.getGroupAllPageList(groupId, page, rows,sort,order);
		
		List<Users> list = p.getList();
		List lists = doOther(userService.convert(list,false));	
		JSONArray jsonArray = JSONArray.fromObject(lists);
		String baseStr = "{\"total\":" + p.getTotalCount() + ",\"rows\":";
		baseStr = baseStr + jsonArray.toString() + "}";
		returnJsion(baseStr,response);
	}
	
	public void findByLoginIds(){
		
		String baseStr ="";
		if(loginids!=null&&!"".equals(loginids)){
			List<Users> list = this.userService.findByLoginIds(loginids);
			List lists = doOther(userService.convert(list,false));	
			JSONArray jsonArray = JSONArray.fromObject(lists);
			if(jsonArray!=null){
				baseStr=jsonArray.toString();
			}
			returnJsion(baseStr,response);
		}
		returnJsion(baseStr,response);
	}
	public void findByName(){
		
		String baseStr ="";
		if(q!=null&&!"".equals(q)){
			List<Users> list = this.userService.findByName(q);
			List lists = doOther(userService.convert(list,false));	
			JSONArray jsonArray = JSONArray.fromObject(lists);
			if(jsonArray!=null){
				baseStr=jsonArray.toString();
			}
			returnJsion(baseStr,response);
		}
		returnJsion(baseStr,response);
	}
	
	/** 
	  * @Title: returnJsion 
	  * @Description: 返回jsion值
	  * @param @param string
	  * @param @param response
	  * @return void
	  * @throws 
	  */
	private void returnJsion(String string,HttpServletResponse response) {
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(string);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
	}
	
	/** 
	  * @Title: doOther 
	  * @Description: 解决struts2.0domal接受参数的方法
	  * @param @param list
	  * @param @return
	  * @return List
	  * @throws 
	  */
	private List doOther(List<CloneUsers> list) {
		List lists = new ArrayList();
		if(list != null && list.size() > 0){
			for(int i =0;i<list.size();i++){
				Map<String,String> map = new HashMap<String, String>();
				CloneUsers user = list.get(i);
				map.put("address",user.getAddress());
				map.put("age",user.getAge());
				map.put("birthday",user.getBirthday());
				map.put("workNumber",user.getWorkNumber());
				map.put("email",user.getEmail());
				map.put("enname",user.getEnname());
				map.put("id",user.getId()+"");
				map.put("lastlogoffdate",user.getLastlogoffdate());
				map.put("lastlogondate",user.getLastlogondate());
				map.put("lastlogonip",user.getLastlogonip());
				map.put("logonid",user.getLogonid());
				map.put("memo",user.getMemo());
				map.put("name",user.getName());
				map.put("orderid",user.getOrderid());
				map.put("password",user.getPassword());
				map.put("phone",user.getPhone());
				map.put("passwdStatus",user.getPasswdStatus());
				map.put("passwdChgDate",user.getPasswdChgDate());
				map.put("registerdate",user.getRegisterdate());
				map.put("sex",user.getSex());
				map.put("status",user.getStatus()+"");
				map.put("usertype",user.getUsertype());
				map.put("deptId",user.getDeptId()+"");
				map.put("deptName",user.getDeptName());
				map.put("companyId",user.getCompanyId());
				map.put("companyName",user.getCompanyName());
				map.put("managerId",user.getManagerId()+"");
				map.put("managerName",user.getManagerName());
				map.put("mobilePhone",user.getMobilePhone());	
				map.put("ext1",user.getExt1());
				map.put("ext2",user.getExt2());
				map.put("ext3",user.getExt3());
				map.put("ext4",user.getExt4());
				map.put("ext5",user.getExt5());
				map.put("ext6",user.getExt6());
				map.put("ext7",user.getExt7());
				
				map.put("isSa",user.getIsSa()+"");
				map.put("photoPath",user.getPhotoPath());
				lists.add(map);
			}
		}
		return lists;
	}
	private void reloadMemory(){
		DictionaryMemoryUtils dictionaryUtils = DictionaryMemoryUtils.getInstance();
		dictionaryUtils.refreshDic(ConstCode.DIC_NICK_NAME_USER, user.getName(), user.getId()+"");
	}
	public void uploadFile()
	{
		String filePath = null;
		try
		{
			String targetDirectory = ServletActionContext.getServletContext()
					.getRealPath("/userPhoto");// 获得路径
			if(upload.length>0)
			{
				String fileName = uploadFileName[0];// 上传的文件名
				String realName ="user_"+id + fileName.substring(fileName.lastIndexOf("."));// 保存的文件名称

				File target = new File(targetDirectory, realName);
				FileUtils.copyFile(upload[0], target);// 上传至服务器的目录
				filePath = ServletActionContext.getServletContext().getContextPath()+"/userPhoto/"+realName;
			}
			outJsonPlainString(response,"{\"success\":true,\"url\":\""+filePath+"\"}");
		} catch (Exception e)
		{
			e.printStackTrace();
			outJsonPlainString(response,"{\"success\":false,\"url\":\""+filePath+"\"}");
		}
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

	public String getGroupId() {
		return groupId;
	}

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}

	/**
	 * @return the groupName
	 */
	public String getGroupName() {
		return groupName;
	}

	/**
	 * @param groupName the groupName to set
	 */
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}


	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String oldPassword) {
		this.newPassword = oldPassword;
	}

	
}	
